package com.jp.knowledge.service;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.callback.JpCallBack;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.NetLogModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.NetLogUtil;
import com.jp.knowledge.util.SharedUtil;
import com.jp.knowledge.webUtil.JavaScriptInterface;
import com.jp.knowledge.webUtil.X5WebView;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tencent.smtt.utils.TbsLog;

/**
 * Created by jiayen on 16/11/17.
 */

public class WebService extends Service {
    private IBinder localBind;
    private Context mContext;

    private X5WebView webView;
//    private String url = "http://debugm.jp580.com/";
//    private String url = "http://192.168.33.24:3001/";
//    private String url = "http://m.jp580.com/";
    private String url = "file:///android_asset/jp580/index.html";

    private LocalBroadcastManager localBroadcastManager;

    private JpApplication application;
    private JpCallBack callBack;

    private Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {
            L.e("WebMainActivity========" + msg.obj.toString());

            JsonObject obj = JsonUtil.getInstance().strToJson(msg.obj.toString());
            if (obj == null) return;
            String type = obj.get("type") == null ? "" : obj.get("type").getAsString();
            if (type.equals("toNative")) {
                if (callBack != null) callBack.done();
            } else if (type.equals("show_web")) {
                L.e("切换了页面成功!");
            } else if (type.equals("postUserDataToNative")) {//h5端登录成功
                try {
                    JsonObject json = obj.get("param").getAsJsonObject();
                    UserData userData = JsonUtil.getInstance().jsonToObject(json, UserData.class);
                    if (userData != null && userData.getIsLogin() == 1) {
                        application.setUserData(userData);

                        //发送登录成功新广播
                        Intent intent = new Intent();
                        intent.setAction(LocalBroadCast.GET_LOGIN_INFO);
                        localBroadcastManager.sendBroadcast(intent);
                        HttpHelper.token = userData.getToken();
                        HttpHelper.uuid = userData.getUuid();
                        SharedUtil.getInstance(mContext).saveTokenAndUUId(HttpHelper.token, HttpHelper.uuid);
                    }

                    L.e("postUserDataToNative", userData.toString());
                } catch (Exception e) {

                }
            } else if (type.equals("set_user_data")) {//设置用户信息回调
                L.e("WebMainActivity", "设置用户信息回调");
            } else if (type.equals("toLibraryDetail")) {//跳到详情
                sendLocalBroadcast(LocalBroadCast.WEB_DOC_DETAIL,
                        obj.get("param").getAsJsonObject().toString());
                goBack();
            } else if(type.equals("toSearch")){//跳转到搜索
                sendLocalBroadcast(LocalBroadCast.TO_SEARCH, obj.get("param").toString());
                goBack();
            } else if(type.equals("toggleTime")){
                sendLocalBroadcast(LocalBroadCast.TOGGLE_TIME, obj.get("param").toString());
            } else if(type.equals("openWebView")){
                sendLocalBroadcast(LocalBroadCast.OPEN_URL_WITH_BROWSER, obj.get("param").toString());
            } else if(type.equals("shujutext")){
                NetLogModel netLogModel = new NetLogModel();
                try {
                    JsonObject param = obj.get("param").getAsJsonObject();
                    netLogModel.setType(param.get("type").getAsString());
                    netLogModel.setRequestTime(param.get("strtime").getAsString());
                    netLogModel.setResponseTime(param.get("endtime").getAsString());
                    netLogModel.setUrl(param.get("url").getAsString());
                    netLogModel.setRequestParam(param.get("param").getAsJsonObject().toString());
                    netLogModel.setErrorCode(Integer.parseInt(param.get("errCode").getAsString()));
                    netLogModel.setMessage(param.get("message").getAsJsonObject().toString());
                } catch (Exception e){} finally {
                    NetLogUtil.saveNetMsgToLocal(netLogModel);
                }
            } else if(type.equals("updateLightExp")){
                sendLocalBroadcast(LocalBroadCast.UPDATE_LIGHT_EXT, obj.get("param").toString());
            }
        }
    };

    private void goBack(){
        if(webView != null)
            webView.loadUrl("javascript:windowNativeBridge.goBack()");
    }

    private void sendLocalBroadcast(String action, String param){
        localBroadcastManager.sendBroadcast(new Intent(action)
                .putExtra("param", param));
    }

    private void sendLoadingCompeleteBroadcast(String url) {
        Intent intent = new Intent(LocalBroadCast.WEB_LOADING_BROAD);
        intent.putExtra("url", url);
        localBroadcastManager.sendBroadcast(intent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        localBind = new LocalBinder();
        L.e("========webservice启动=====onBind====");
        return localBind;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }


    public void setCallBack(JpCallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        L.e("========webservice启动=====onCreate====");
        application = (JpApplication) getApplication();
        application.addService(this);
        mContext = getApplicationContext();
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        webView = initWebView();
        if (webView != null) {
            webView.getSettings().setUserAgentString("app_jp;jp580.com");
            webView.addJavascriptInterface(new JavaScriptInterface(mHandler), "Android");
            X5WebView.setSmallWebViewEnabled(true);// 开启webview窗口转移功能
            webView.loadUrl(url);
        }
    }

    /**
     * 设置用户信息到h5里面
     *
     * @param userData
     */
    public void setUserData(UserData userData) {
        String data = userData == null ? "{}" : JsonUtil.getInstance().objToJson(userData);
        JsonObject obj = new JsonObject();
        obj.addProperty("type", "set_user_data");
        L.e("本次设置h5的用户信息为:" + data);
//		contView.loadUrl("javascript:windowNativeBridge.setUserInfoData('"+data+"',Android.jsCallback('"+obj.toString()+"'))");
        webView.loadUrl("javascript:windowNativeBridge.setUserInfoData('" + data + "','" + obj.toString() + "')");
    }


    /**
     * 设置webview的路径
     *
     * @param path
     * @param path
     */
    public void setCurrentPath(String path) {
        this.currentPath = path;
        if (webView != null) {
//            webView.clearView();
            webView.loadUrl("javascript:windowNativeBridge.setCurrentPath('" + path + "')");
        } else
            ToasUtil.toast(mContext, "对象为空！");
    }
    private String currentPath;
    public String getCurrentPath(){
        return this.currentPath;
    }

    public class LocalBinder extends Binder {
        public WebService getService() {
            return WebService.this;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        L.e("WebService", "======销毁webservice=======");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        L.e("========webservice启动=====onStartCommand====");
        return super.onStartCommand(intent, flags, startId);
    }

    public X5WebView getWebView() {
        return webView;
    }


    private X5WebView initWebView() {
        try {


            Log.e("0819", " before is " + System.currentTimeMillis());
            final X5WebView mWebView = new X5WebView(this);
            Log.e("0819", " after is " + System.currentTimeMillis());

            Log.w("grass", "Current SDK_INT:" + Build.VERSION.SDK_INT);

            mWebView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    return false;
                }

                @Override
                public WebResourceResponse shouldInterceptRequest(WebView view,
                                                                  WebResourceRequest request) {
                    // TODO Auto-generated method stub

                    Log.e("should", "request.getUrl().toString() is " + request.getUrl().toString());

                    return super.shouldInterceptRequest(view, request);
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    sendLoadingCompeleteBroadcast(url);
                    if((WebService.this.url + "#/").equals(url))
                        webView.loadUrl("javascript:windowNativeBridge.setInWebView(2)");
                }

                @Override
                public void onReceivedError(WebView webView, int i, String s, String s1) {
                    L.e("onReceivedError", "网页加载错误......." + "i=" + i + "=====s=" + s + "===s1=" + s1);

                }

            });

            mWebView.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onReceivedTitle(WebView view, String title) {
                    L.d("title: " + title);
//				if (!mWebView.getUrl().equalsIgnoreCase(mHomeUrl)) {
//				} else {
//				}
                }

                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    // TODO Auto-generated method stub
                    final int progress = newProgress;

                }
            });

            mWebView.setDownloadListener(new DownloadListener() {

                @Override
                public void onDownloadStart(String arg0, String arg1, String arg2,
                                            String arg3, long arg4) {
                    L.d("url: " + arg0);
                    new AlertDialog.Builder(mContext)
                            .setTitle("你即将下载")
                            .setPositiveButton("yes",
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            ToasUtil.toast(
                                                    mContext,
                                                    "fake message: i'll download...");
                                        }
                                    })
                            .setNegativeButton("no",
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            // TODO Auto-generated method stub
                                            ToasUtil.toast(
                                                    mContext,
                                                    "fake message: refuse download...");
                                        }
                                    })
                            .setOnCancelListener(
                                    new DialogInterface.OnCancelListener() {

                                        @Override
                                        public void onCancel(DialogInterface dialog) {
                                            // TODO Auto-generated method stub
                                            ToasUtil.toast(
                                                    mContext,
                                                    "fake message: refuse download...");
                                        }
                                    }).show();
                }
            });


            WebSettings webSetting = mWebView.getSettings();
            webSetting.setAllowFileAccess(true);
            webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
            webSetting.setSupportZoom(false);
            webSetting.setBuiltInZoomControls(false);
            webSetting.setUseWideViewPort(true);
            webSetting.setSupportMultipleWindows(false);
            webSetting.setLoadWithOverviewMode(true);
            webSetting.setAppCacheEnabled(true);
            webSetting.setDatabaseEnabled(true);
            webSetting.setDomStorageEnabled(true);
            webSetting.setJavaScriptEnabled(true);
            webSetting.setGeolocationEnabled(true);
            webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
            webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
            webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
            webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                    .getPath());
            webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
            webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
            long time = System.currentTimeMillis();
            TbsLog.d("time-cost", "cost time: "
                    + (System.currentTimeMillis() - time));
            CookieSyncManager.createInstance(this);
            CookieSyncManager.getInstance().sync();
            return mWebView;
        } catch (Exception e) {

        }
        return null;
    }
}
